package com.dhcc.dubbo.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import com.dhcc.dubbo.bean.response.Result;
import com.dhcc.dubbo.bean.response.ResultCode;
import com.dhcc.dubbo.exception.CommonException;

/**
 * 自定义的公共异常处理器
 *      1.声明异常处理器
 *      2.对异常统一处理
 */
@ControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result error(HttpServletRequest request, HttpServletResponse response,Exception e) {
        e.printStackTrace();
        if(e.getClass() == CommonException.class) {
            //类型转型
            CommonException ce = (CommonException) e;
            Result result = new Result(ce.getResultCode());
            return result;
        }else{
        	//系统内部错误，请用ResultCode.SERVER_ERROR
        	//如果对外提供服务，请把错误信息返回给第三方
            Result result = new Result(9999,e.getMessage(),false);
//            Result result = new Result(ResultCode.SERVER_ERROR);
            return result;
        }
    }

    //捕获NumberFormatException异常类型
    @ExceptionHandler(value = NumberFormatException.class)
    @ResponseBody
    public Result error(HttpServletRequest request, HttpServletResponse response,NumberFormatException e) {
        return new Result(ResultCode.NOINPUTTYPE);
    }
    //捕获MethodArgumentTypeMismatchException异常类型
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Result error(HttpServletRequest request, HttpServletResponse response,MethodArgumentTypeMismatchException e) {
    	return new Result(ResultCode.ARGUMENTTYPE_ERROR);
    }
    //捕获ArithmeticException异常类型
    @ExceptionHandler(value = ArithmeticException.class)
    @ResponseBody
    public Result error(HttpServletRequest request, HttpServletResponse response,ArithmeticException e) {
        return new Result(ResultCode.ARITHMETIC_ERROR);
    }
}
